﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Linq.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using jSLApp.Web.Workflow;
using jSLCore.Service.Workflow;

namespace jSLApp.Web
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            jSLCore.Service.jSLAuthorizationServiceBase.ConnectionString =
                ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;

            using (var db= new DB())
            {
                if(MainService.GetVisit(Request,db)==null)
                {
                    var visit = Request.CreateVisit();
                    db.Visits.InsertOnSubmit(visit);
                    db.SubmitChanges();
                }
            }
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var ext = Request.CurrentExecutionFilePathExtension.ToUpper();
            if(ext==".WMV" || ext==".ISM")
            {
                var filePath = Request.CurrentExecutionFilePath;

                var sessionName = string.Format("fa:{0}",filePath);

                if(Session[sessionName]==null || (bool)Session[sessionName]!=true)
                {
                    CheckMediaAccessRights();
                    Session.Add(sessionName,true);
                }
            }
        }

        private void CheckMediaAccessRights()
        {
            var fileName = Request.Url.LocalPath.Remove(0,1);

            CheckAccessToFilmByFileName(fileName);
        }

        private void CheckAccessToFilmByFileName(string fileName)
        {
            using (var db = new DB())
            {
                var film = db.Films.SingleOrDefault(f=>SqlMethods.Like(f.TrailerUri,fileName));
                if(film!=null)
                {
                    return;//ok
                }

                film = db.Films.SingleOrDefault(f => SqlMethods.Like(f.SourceUri,fileName));

                if(film!=null)
                {
                    if(MainService.IsFilmAccessedByCurrentUser(db,film))
                    {
                        return;//ok
                    }
                    ThrowUnauthorized();
                }

                ThrowUnauthorized();
            }
        }

        private void ThrowUnauthorized()
        {
            Response.Status = "401 Unauthorized";
            Response.StatusCode = 401;
            Response.Flush();

            throw new UnauthorizedAccessException("Попытка доступа к источнику мультимедиа не из приложения");
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }



        protected void Application_Error(object sender, EventArgs e)
        {
            
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}